package com.chat.common.user.service.impl;

import cn.hutool.core.util.StrUtil;
import com.chat.common.chat.domain.dto.LoginMessageDTO;
import com.chat.common.chat.domain.dto.ScanSuccessMessageDTO;
import com.chat.common.common.constant.MQConstant;
import com.chat.common.user.dao.UserDao;
import com.chat.common.user.domain.entity.User;
import com.chat.common.user.service.UserService;
import com.chat.common.user.service.WxMsgService;
import com.chat.common.user.service.adapter.TextBuilder;
import com.chat.common.user.service.adapter.UserAdapter;
import com.chat.common.websocket.service.WebSocketService;
import com.chat.transaction.service.MQProducer;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Slf4j
public class WxMsgServiceImpl implements WxMsgService {

    @Resource
    private UserDao userDao;
    @Resource
    private UserService userService;

    @Resource
    @Lazy
    private WxMpService wxMpService;

    @Resource
    private WebSocketService webSocketService;
    @Resource
    private MQProducer mqProducer;

    @Value("${wx.mp.callback}")
    private String callback;
    private static final String URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";

    /**
     * openid 和登录 code的关系
     */
    private static final ConcurrentHashMap<String,Integer> WAIT_AUTHORIZE_MAP = new ConcurrentHashMap<>();

    @Override
    public WxMpXmlOutMessage scan(WxMpXmlMessage wxMpXmlMessage) {
        String openId = wxMpXmlMessage.getFromUser();
        Integer code = getEventKey(wxMpXmlMessage);
        if(Objects.isNull(code)){
            return null;
        }
        //已经关注过公众号的用户 根据用户的openid 查询用户信息
        User user = userDao.GetByOpenId(openId);
        //是否扫过码
        //false
        boolean register = Objects.nonNull(user);
        // 用户是否点击授权链接 是否取到了 用户的头像
        boolean authorized =register&& StrUtil.isNotBlank(user.getAvatar());
        if(register&&authorized){
            //登录成功的逻辑 就是通过code找到channel 推送消息
//            webSocketService.scanLoginSuccess(code,user.getId());
            mqProducer.sendMsg(MQConstant.LOGIN_MSG_TOPIC, new LoginMessageDTO(user.getId(), code));
            return null;
        }
        //用户未注册 用户已经关注了公众号 并非通过扫码关注 为用户insert 一个账号 根据openid
        if(!register){
            //构建 一个user 对象
            User insert = UserAdapter.buildUserSave(openId);
            userService.register(insert);
        }

        // 扫码事件处理
        String fromUser = wxMpXmlMessage.getFromUser();
        WAIT_AUTHORIZE_MAP.put(openId,code);
        //并且将状态通知到前端
//        webSocketService.waitAuthorize(code);
        //授权流程,给用户发送授权消息，并且异步通知前端扫码成功,等待授权
        mqProducer.sendMsg(MQConstant.SCAN_MSG_TOPIC, new ScanSuccessMessageDTO(code));
        //扫码
        String skipUrl = String.format(URL, wxMpService.getWxMpConfigStorage().getAppId(), callback + "/wx/portal/public/callBack");
        return TextBuilder.build("请点击链接授权：<a href=\"" + skipUrl + "\">登录</a>",wxMpXmlMessage, wxMpService);
    }


    //完成回调 清空 map中的数据
    @Override
    public void authorize(WxOAuth2UserInfo userInfo) {
        String openid = userInfo.getOpenid();
        User user = userDao.GetByOpenId(openid);
        //更新用户信息 如果查询到用户的头像为null 我们就从微信回调函数获取的信息去更新用户的头像名字
        if(!StrUtil.isNotBlank(user.getAvatar())){
            fillUserInfo(user.getId(), userInfo);
        }
        //通过用户的code 获取对应的channel
        Integer code = WAIT_AUTHORIZE_MAP.remove(openid);
//        Boolean b = webSocketService.scanLoginSuccess(code, user.getId());
        mqProducer.sendMsg(MQConstant.LOGIN_MSG_TOPIC, new LoginMessageDTO(user.getId(), code));
    }

    private void fillUserInfo(Long id, WxOAuth2UserInfo userInfo) {
        User authorize = UserAdapter.BuildAuthorize(id, userInfo);
        log.info("用户回调函数更新用户头像名称{}",authorize);
        userDao.updateById(authorize);
    }

    private Integer getEventKey(WxMpXmlMessage wxMpXmlMessage) {
      try {
          String eventKey = wxMpXmlMessage.getEventKey();
          String code = eventKey.replace("qrscene_", "");
          return Integer.parseInt(code);
      }catch (Exception e){
            log.error("EventKey Get Error{}",wxMpXmlMessage.getEventKey(),e);
            return null;
      }
    }
}
